package com.qf.im.controller;

import com.qf.im.base.R;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.uploaderpath}")
    private String fileUploaderPath;

    /**
     * 文件上传的接口
     * @return
     */
    @PostMapping("/uploader")
    public R uploader(MultipartFile file){
        File myfile = new File(fileUploaderPath);
        if (!myfile.exists()) {
            myfile.mkdirs();
        }

        //文件名
        String fileName = UUID.randomUUID().toString();
        try (
                //网络输入流
                InputStream in = file.getInputStream();
                //输出流
                OutputStream out = new FileOutputStream(fileUploaderPath + File.separator + fileName);
        ){
            //输入流拷贝到输出流
            IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //返回上传后的文件名，为了方便后续下载这个文件
        return R.succ(fileName);
    }

    /**
     * 文件下载
     * @return
     */
    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response){

        File file  = new File(fileUploaderPath + "\\" + fileName);

        try(
                //要下载的文件流
                FileChannel in = new FileInputStream(file).getChannel();
                //输出的网络流
                WritableByteChannel out = Channels.newChannel(response.getOutputStream());
        ) {
            //文件拷贝
//            IOUtils.copy(in, out);
            //改造成0拷贝（zero-copy）
            in.transferTo(0, file.length(), out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
